package mk.jug.academy.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import mk.jug.academy.model.Page;
import mk.jug.academy.model.Sponsor;
import mk.jug.academy.model.SponsorStatus;

import org.springframework.stereotype.Repository;


/**
 * DAO for the {@link Sponsor} entity model.
 *
 * @author Ice.Penov
 */
@Repository
public class SponsorDAO extends GenericDAO<Sponsor> {
	
	/**
	 * Returns the {@link Sponsor}s with the given status,
	 * ordered by their rating, considering the given boundaries.
	 */
	public Page<Sponsor> findByStatus(final SponsorStatus status, final int start, final int end) {
		return new QueryEMContext<Page<Sponsor>>() {
			@Override @SuppressWarnings("unchecked")
			public Page<Sponsor> query(EntityManager em) {
				Query query = em.createQuery("Select s from mk.jug.academy.model.Sponsor s where s.status = :status order by s.rating desc");
				query.setParameter("status", status);
				query.setFirstResult(start);
				query.setMaxResults(end);
				List<Sponsor> list = query.getResultList();
				query = em.createQuery("Select count(s.id) from mk.jug.academy.model.Sponsor s where s.status = :status");
				query.setParameter("status", status);
				return new Page<Sponsor>(initialize(list), (Integer) query.getSingleResult());
			}
		}.result();
	}

	/**
	 * Fetch the ACTIVE Sponsor with the given email.
	 */
	public Sponsor findActiveByEmail(final String email) {
		return new QueryEMContext<Sponsor>() {
			@Override
			public Sponsor query(EntityManager em) {
				Query query = em.createQuery("Select s from mk.jug.academy.model.Sponsor s where s.email = :email and s.status = :status");
				query.setParameter("email", email);
				query.setParameter("status", SponsorStatus.ACTIVE);
				return (Sponsor) query.getSingleResult();
			}
		}.result();
	}
	
	/**
	 * Fetch ANY Sponsor with the given email.
	 */
	public Sponsor findAnyByEmail(final String email) {
		return new QueryEMContext<Sponsor>() {
			@Override
			public Sponsor query(EntityManager em) {
				Query query = em.createQuery("Select s from mk.jug.academy.model.Sponsor s where s.email = :email");
				query.setParameter("email", email);
				return (Sponsor) query.getSingleResult();
			}
		}.result();
	}	

}